package com.itheima.dubbo.api;

import com.tanhua.domain.mogo.Friend;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.api.FriendApi;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service

public class FriendApiImpl  implements FriendApi {
    //添加联系人
    @Autowired
    private MongoTemplate mongoTemplate;

    //分页查询某用户的联系人列表
    @Override
    public PageResult<Friend> findFriendList(int page, int pagesize, String keyword, long userId) {
        Query query = new Query(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Order.desc("created")))
                .with(PageRequest.of(page-1,pagesize));
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        long count=mongoTemplate.count(query,Friend.class);
        int pages= (int) Math.ceil(count*1.0/pagesize);

        return new PageResult<>((int)count,page,pages,pagesize,friendList);
    }

    @Override
    public void addFriend(Long userId1, Long userId2) {
        //给userID1添加好友 userid2
        boolean exists = mongoTemplate.exists(new Query(Criteria.where("userId").is(userId1).and("friendId").is(userId2)), Friend.class);
        if (!exists){
            Friend friend = new Friend();
            friend.setId(ObjectId.get());
            friend.setUserId(userId1);
            friend.setFriendId(userId2);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }
        //给userID2 添加好友 userId1
         exists = mongoTemplate.exists(new Query(Criteria.where("userId").is(userId2).and("friendId").is(userId1)), Friend.class);
        if (!exists){
            Friend friend = new Friend();
            friend.setId(ObjectId.get());
            friend.setUserId(userId2);
            friend.setFriendId(userId1);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);

        }


    }
}
